package org.vnl.platform.web.util;

import java.io.IOException;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.vnl.platform.orm.PersistenceManagerFactory;


public class SinglePersistenceManagerFilter implements Filter {

    private String pmName;
    @Override
    public void destroy() {
        this.pmName = null;
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        PersistenceManagerFactory.getInstance().getPM(this.pmName);
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        String tmp = arg0.getInitParameter("PERSISTENCE_MANAGER_NAME");
        if (StringUtils.isBlank(tmp)) {
            throw new ServletException("PERSISTENCE_MANAGER_NAME not found");
        }
        this.pmName = tmp;
    }

}
